<template>
  <!--开始考试-->
  <div class="app-container">
    <el-row :gutter="24">
    <!--头部-->
    <el-col :span="24">
      <el-card style="margin-bottom: 10px;background: #22944E;color: #fff;text-align: center;">
        <span style="float: left;font-size: 16px">距离考试结束还有 ：<span style="color: #FFF000;font-size: 20px">{{hours}}小时{{ min }}分钟{{ sec }}秒</span></span>
        <span style="font-size: 20px;font-weight: 700">{{examName}}</span>
        <el-button style="font-size: 20px;float: right; margin-top: -10px;color: #22944E;background: #fff;font-weight: 700" type="primary" icon="el-icon-plus" :loading="loading" @click="handHandExam">
          {{ handleText }}
        </el-button>
      </el-card>
    </el-col>
    <!--答题卡-->
    <el-col :span="6" :xs="24" style="margin-bottom: 10px;width: 380px;" class="datika">
      <el-card style="padding-bottom: 60px;">
        <div class="card-title" style="background: #22944E;color: #fff">答题卡</div>
        <el-row :gutter="24" class="card-line" style="margin-left: 20px;margin-top: 16px">
          <el-tag type="info" style="width: 60px;height: 28px;line-height: 28px;font-size: 14px;">未作答</el-tag>
          <el-tag type="success" style="width: 60px;height: 28px;line-height: 28px;font-size: 14px;">已作答</el-tag>
          <el-tag type="success" style="width: 60px;height: 28px;line-height: 28px;font-size: 14px;background: #FFFAE4;color: #FFCC00; border: 1px solid #FFF0B2;">当前</el-tag>
        </el-row>
        <div v-if="paperData.radioList!==undefined && paperData.radioList.length > 0">
          <p class="card-title">一、单选题</p>
          <el-row :gutter="24" class="card-line" style="margin-left: 20px;margin-right: 20px">
            <el-tag v-for="(item1,index1) in paperData.radioList" :type="cardItemClass(item1.examQuestion, index1)" @click="handSave(index1)" :key="index1"> {{ index1+1 }}</el-tag>
          </el-row>
        </div>

        <div v-if="paperData.multiList!==undefined && paperData.multiList.length > 0">
          <p class="card-title">二、多选题</p>
          <el-row :gutter="24" class="card-line" style="margin-left: 20px;margin-right: 20px">
            <el-tag v-for="(item2,index2) in paperData.multiList" :type="cardItemClass(item2.examQuestion, a+index2)" @click="handSave(a+index2)" :key="index2">{{ a+index2+1 }}</el-tag>
          </el-row>
        </div>

        <div v-if="paperData.judgeList!==undefined && paperData.judgeList.length > 0">
          <p class="card-title">三、判断题</p>
          <el-row :gutter="24" class="card-line" style="margin-left: 20px;margin-right: 20px">
            <el-tag v-for="(item3,index3) in paperData.judgeList" :type="cardItemClass(item3.examQuestion, b+index3)" @click="handSave(b+index3)" :key="index3">{{ b+index3+1 }}</el-tag>
          </el-row>
        </div>

        <div v-if="paperData.saqList!==undefined && paperData.saqList.length > 0">
          <p class="card-title">四、简答题</p>
          <el-row :gutter="24" class="card-line" style="margin-left: 20px;margin-right: 20px">
            <el-tag v-for="(item4,index4) in paperData.saqList" :type="cardItemClass(item4.examQuestion, c+index4)" @click="handSave(c+index4)" :key="index4">{{ c+index4+1 }}</el-tag>
          </el-row>
        </div>
      </el-card>
    </el-col>
    <!--答题区-->
      <div v-for="(item,index) in questionDto" :key="index">
        <el-col :span="18" :xs="24" style="width: 842px;" v-if="indexNow == index">
          <el-card class="qu-content">
            <p>{{ index + 1 }}.{{ item.examQuestionVO.questionTitle }}</p>
            <!--单选题-->
            <div v-if="index < a || (b <= index && index < c)">
              <el-radio-group v-model="item.examQuestion">
                <el-radio v-for="(item5,index5) in item.questionOptions" :label="item5.code" :key="index5">{{ item5.code }}.{{ item5.content }}</el-radio>
              </el-radio-group>
            </div>
            <!--多选题-->
            <div v-if="a <= index && index < b">
              <el-checkbox-group v-model="item.examQuestion">
                <el-checkbox v-for="(item6,index6) in item.questionOptions" :label="item6.code" :key="index6">{{ item6.code }}.{{ item6.content }}</el-checkbox>
              </el-checkbox-group>
            </div>
            <!--判断题-->
            <!--<div v-if="b <= index && index < c">-->
              <!--<el-radio-group v-model="item.examQuestion">-->
                <!--<el-radio :label="0">A.对</el-radio>-->
                <!--<el-radio :label="1">B.错</el-radio>-->
              <!--</el-radio-group>-->
            <!--</div>-->
            <!--简答题-->
            <div v-if="c <= index && index < d">
              <el-input v-model="item.examQuestion" type="textarea" :rows="10" />
            </div>
          </el-card>

          <div style="margin-top: 20px">
            <el-button v-if="indexNow!=0&&indexNow == index" type="warning" icon="el-icon-back" style="font-size: 20px;" @click="handPrevious()">
              上一题
            </el-button>

            <el-button v-if="indexNow!=questionDto.length-1&&indexNow == index" type="warning" icon="el-icon-right" style="background: #22944E;border-color: #22944E;font-size:20px;box-shadow: 2px 6px 12px 0px rgba(34, 148, 78, 0.2);" @click="handNext()">
              下一题
            </el-button>
          </div>
        </el-col>
      </div>
  </el-row>
  </div>
</template>

<script>
  import { Loading } from 'element-ui'
  import { beginExam,updateExamAnswerRecord,submitExam,testExam ,sendCertificate,examRecordqrcode,questionOptionquery} from '@/request/api'
  import { formatDate } from '@/utils'

  export default {
    name: 'ExamProcess',
    data() {
      return {
        showPrevious: false,
        showNext: true,
        loading: false,
        handleText: '交卷',
        pageLoading: false,
        // 试卷ID
        paperId: '',
        // 试卷信息
        paperData: {
          leftSeconds: 120,
          radioList: [], // 单选
          multiList: [], // 多选
          judgeList: [], // 判断
          saqList: [] // 简答
        },
        questionDto: [],//全部题目包括答案解析

        hours: '00',
        min: '00',
        sec: '00',
//        有多少道什么题
        a: 0,
        b: 0,
        c: 0,
        d: 0,
        indexNow: 0,//目前正在答的题
        examName: '',//试卷名称
        btime: '',//开始答题时间
        passGrade: '',//及格分
        recordId: '',//记录id
      }
    },
    created() {
      if(this.$route.params.type==0) {
//          模拟考试
        this.getMN()
      }else{
//          开始考试
        const id = this.$route.params.id
        if (typeof id !== 'undefined') {
          this.paperId = id
          this.getSJ()
//          this.getQuery(9)
        }
      }
    },
    methods: {
//        获取试卷
      getSJ() {
        var params1 = {
          "BTime": '',
          "ETime": '',
          "ascroe": '',
          memberId: JSON.parse(localStorage.getItem('userInfo')).id,
          "eid": JSON.parse(localStorage.getItem('userInfo')).userType,
          "examinationInfoID": this.paperId
        }
        beginExam(params1).then(res => {
          if (res.code == 200) {
            this.examName= res.data.exam.exam_name
            this.recordId= res.data.examRecord.id
            this.passGrade= Number(res.data.exam.pass_grade)
            this.questionDto = res.data.questionDto
           this.paperData = {
              leftSeconds: this.$route.params.time * 60,
                radioList: [], // 单选
                multiList: [], // 多选
                judgeList: [], // 判断
                saqList: [] // 简答
            },
             this.a = res.data.totalMap['0']
             this.b = this.a+res.data.totalMap['1']
             this.c = this.b+res.data.totalMap['2']
             this.d = this.c+res.data.totalMap['3']
            this.questionDto.forEach((item,index)=> {
                if(index<this.a) {
                  this.paperData.radioList.push(item)
                }else if(this.a <= index && index < this.b){
                    item.examQuestion = []
                  this.paperData.multiList.push(item)
                }else if(this.b <= index && index < this.c){
                  item.examQuestion = ''
                  this.paperData.judgeList.push(item)
                }else if(this.c <= index && index < this.d){
                  item.examQuestion = ''
                  this.paperData.saqList.push(item)
                }
            })
//            开始答题时间
            this.btime = formatDate(new Date())
            // 倒计时
            this.countdown()
          }
        })
      },
      //获取模拟考试试卷
      getMN() {
        testExam().then(res => {
          if (res.code == 200) {
            this.examName= '模拟考试'
            this.questionDto = res.data.questionDto
            this.paperData = {
              leftSeconds: 120 * 60,
              radioList: [], // 单选
              multiList: [], // 多选
              judgeList: [], // 判断
              saqList: [] // 简答
            },
              this.a = res.data.totalMap['0']
            this.b = this.a+res.data.totalMap['1']
            this.c = this.b+res.data.totalMap['2']
            this.d = this.c+res.data.totalMap['3']
            this.questionDto.forEach((item,index)=> {
                var par = {
              "_search": false,
                "selectedType": "question_id",
                "type":  item.examQuestionVO.questionId
                }
              questionOptionquery(par).then(res1 => {
                item.questionOptions = res1.data.records
                if(index<this.a) {
                  item.examQuestion = ''
                  this.paperData.radioList.push(item)
                }else if(this.a <= index && index < this.b){
                  item.examQuestion = []
                  this.paperData.multiList.push(item)
                }else if(this.b <= index && index < this.c){
                  item.examQuestion = ''
                  this.paperData.judgeList.push(item)
                }else if(this.c <= index && index < this.d){
                  item.examQuestion = ''
                  this.paperData.saqList.push(item)
                }
              })
            })
//            开始答题时间
            this.btime = formatDate(new Date())
            // 倒计时
            this.countdown()
          }
        })
      },
      // 倒计时
      countdown() {
        const leftSeconds = this.paperData.leftSeconds
        // 强制交卷
        if (leftSeconds < 0) {
          this.doHandler()
          return
        }
        // 时
        const hours = parseInt(leftSeconds / 60 / 60 % 24 , 10)
        const min = parseInt(leftSeconds / 60 % 60)
        const sec = parseInt(leftSeconds % 60)

        this.hours = hours > 9 ? hours : '0' + hours
        this.min = min > 9 ? min : '0' + min
        this.sec = sec > 9 ? sec : '0' + sec
        const that = this
        this.paperData.leftSeconds -= 1
        setTimeout(function () {
          that.countdown()
        }, 1000)
      },
      // 答题卡样式
      cardItemClass(answered, index) {
        if (index === this.indexNow) {
          return 'warning'
        }else if (answered!=null&&answered!=''&&answered!=[]) {
          return 'success'
        }else {
          return 'info'
        }
      },
      /**
       * 统计有多少题没答的
       * @returns {number}
       */
      countNotAnswered() {
        let notAnswered = 0
        var that = this
        this.questionDto.forEach(function (item,index) {
          if(index<that.a || (that.b <= index && index < that.c)) {
            if(item.examQuestion==null||item.examQuestion=='') {
              notAnswered = notAnswered+1
            }
          }else if(that.a <= index && index < that.b){
            if(item.examQuestion.length==0) {
              notAnswered = notAnswered+1
            }
          }else if(that.c <= index && index < that.d){
            if(item.examQuestion==null||item.examQuestion=='') {
              notAnswered = notAnswered+1
            }
          }
        })
        return notAnswered
      },
      /**
       * 下一题
       */
      handNext() {
        this.handleText = '加载中。。。'
        this.loading = true
        setTimeout(e=> {
          this.indexNow++
          this.handleText = '交卷'
          this.loading = false
        },500)
      },
      /**
       * 上一题
       */
      handPrevious() {
        this.handleText = '加载中。。。'
        this.loading = true
        setTimeout(e=> {
          this.indexNow--
          this.handleText = '交卷'
          this.loading = false
        },500)
      },
//      去往第几题
      handSave(index) {
        this.handleText = '加载中。。。'
        this.loading = true
        setTimeout(e=> {
          this.indexNow = index
          this.handleText = '交卷'
          this.loading = false
        },500)
      },
//      保存题目答案
      bctm(){
        const loading = this.openLoading();
        var breaks = false
        var tscroe = 0
        console.log('this.questionDto:' + this.questionDto[0]);
        this.questionDto.forEach((e,index)=>{
          console.log('breaks:' + breaks + index);
          if(breaks == false) {
//                题目类型
              if(index<this.a) {
                var questionType = 0
              }else if(this.a <= index && index < this.b){
                var questionType = 1
              }else if(this.b <= index && index < this.c){
                var questionType = 2
              }else if(this.c <= index && index < this.d){
                var questionType = 3
              }
//              是否正确，得几分
              if(e.examQuestion!=null||e.examQuestion!='') {
                var sign =1

                if(questionType ==1) {
                  //多选题v-model是[]
                  var breakss = false
                  var questionAnswer = e.examQuestionVO.questionAnswer.split(',')
                  questionAnswer.forEach(i=> {
                    if(breakss = false) {
                      if(e.examQuestion.indexOf('i')== -1) {
                        breakss = true
                      }
                    }
                  })
                  if(breakss == false) {
                    var isOK = 1
                    var score = e.examQuestionVO.grade
                  }else {
                    var isOK = 0
                    var score = 0
                  }
                }
//                else if(questionType ==2){
//                  //判断题是0,1
//                  if(e.examQuestion==0&&e.examQuestionVO.questionAnswer=='对') {
//                    var isOK = 1
//                    var score = e.examQuestionVO.grade
//                  }else if(e.examQuestion==1&&e.examQuestionVO.questionAnswer=='错') {
//                    var isOK = 1
//                    var score = e.examQuestionVO.grade
//                  }else {
//                    var isOK = 0
//                    var score = 0
//                  }
//                }
                else{
                  if(e.examQuestion==e.examQuestionVO.questionAnswer) {
                    var isOK = 1
                    var score = e.examQuestionVO.grade
                  }else {
                    var isOK = 0
                    var score = 0
                  }
                }
              }else {
                var sign =0
              }

              if(questionType !=1) {
                var examQuestion = e.examQuestion
              }else {
                var examQuestion = e.examQuestion.join(',')
              }
              if(this.$route.params.type==0) {
                var examAnswerId = e.examQuestionVO.examId
                var examAnswerQuestionId = e.examQuestionVO.questionId
              }else {
                  var examAnswerId = e.examAnswerRecord.id
                  var examAnswerQuestionId = e.examAnswerRecord.questionId
              }
              var params = {
                "ATime": "",
                "answer": examQuestion,
                "answerReply": examQuestion,
                "atime": "",
                "examTitleID": this.paperId,//试卷id
                "id": examAnswerId,// 考试题目记录id
                "isOK": isOK,//是否答对
                "memberID": JSON.parse(localStorage.getItem('userInfo')).id,// 会员ID 用户id
                "questionId": examAnswerQuestionId,
                "questionType": questionType, // 题目类型
                "score": score, // 得分 如果是简答题 默认得分0
                "sign": sign, // 是否作答
                "userTime": 0
              }
              tscroe = tscroe + score
              updateExamAnswerRecord(params).then(res=> {
                if(res.code==200) {
                  breaks = false
                  if(index == this.questionDto.length-1 && this.$route.params.type==1) {
                    this.doHandler(tscroe)
                  }else if(this.$route.params.type==0){
                    this.$router.push({name: 'home'})
                  }
                }else {
                  breaks = true
                }
              }).catch(eo=>{
                breaks = true
              })
            }else {
              loading.close();
              this.$message({
                type: 'info',
                message: '答案保存失败,请重试！',
                offset: '500'
              })
            }
        })
      },
//      交卷
      doHandler(tscroe) {
        if(this.paperData.saqList!==undefined && this.paperData.saqList.length > 0) {
            var isCheck = 2//未阅
        }else {
          var isCheck = 1//已阅
        }
        const params = {
          "BTime": "",
          "ETime": "",
          "ascroe": tscroe,
          "score": tscroe,
          "btime": this.btime,
          "eid": JSON.parse(localStorage.getItem('userInfo')).userType,
          "ename": this.examName,
          "etime":  formatDate(new Date()),
          "examinationInfoID": this.paperId,
          "id":this.recordId,
          "tscroe": '',
          memberId: JSON.parse(localStorage.getItem('userInfo')).id,
          recordId: this.recordId,
          isCheck: isCheck
//          isCheck: 2
        }
        submitExam(params).then((res) => {
            if(res.code==200) {
              this.$message({
                message: '试卷提交成功!',
                type: 'success',
                offset: '500'
              })
              this.getQuery(tscroe)
            }else {
              this.$message({
                message: res.msg,
                type: 'info',
                offset: '500'
              })
            }
        })
      },
      // 交卷操作
      handHandExam() {
        const that = this
        // 交卷保存答案
        const notAnswered = that.countNotAnswered()
        let msg = '确认要交卷吗？'
        if (notAnswered > 0) {
          msg = '您还有' + notAnswered + '题未作答，确认要交卷吗?'
        }
        that.$confirm(msg, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          that.bctm()
        }).catch(() => {
          that.$message({
            type: 'info',
            message: '交卷已取消，您可以继续作答！'
          })
        })
      },
      //发放证书
      getQuery(tscroe) {
          //只有企业通过考试及格才能发放证书
          if(JSON.parse(localStorage.getItem('userInfo')).userType==0 && this.$route.params.type!=0 && tscroe>=this.passGrade) {
            sendCertificate({memberId:JSON.parse(localStorage.getItem('userInfo')).id}).then(res=> {
                if(res.code==200) {
                  setTimeout(e => {
                    if (this.paperData.saqList !== undefined && this.paperData.saqList.length > 0) {
                      this.$router.push({name: 'examList'})
                    } else {
                      this.$router.push({name: 'paperAnalysisInfo', params: {id: this.paperId}})
                    }
                  }, 1000)
                }
            })
          }else{
            setTimeout(e=> {
              if(this.paperData.saqList!==undefined && this.paperData.saqList.length > 0) {
                this.$router.push({ name: 'examList'})
              }else {
                this.$router.push({ name: 'paperAnalysisInfo',params:{id:this.paperId}})
              }
            },1000)
          }
      }
    }
  }
</script>

<style scoped>
  .web-cam{
    position: absolute;
    right: 5px;
    bottom: 10px;
  }
  .qu-content{

  }
  .qu-content div{
    line-height: 30px;
  }
  .el-checkbox-group label,.el-radio-group label{
    width: 100%;
    box-sizing: border-box;
  }
  .card-title{
    background: rgba(34, 148, 78, 0.2);
    color: #22944E;
    height: 40px;
    line-height: 40px;
    /*text-align: center;*/
    padding-left: 20px;
    font-size: 18px;
    font-weight: bold;
  }
  .card-line{
    /*padding-left: 10px*/
  }
  .card-line span {
    cursor: pointer;
    margin: 2px;
  }
  /deep/
  .el-radio, .el-checkbox{
    padding: 9px 20px 9px 10px;
    border-radius: 4px;
    border: 1px solid #dcdfe6;
    margin-bottom: 10px;
  }
  .is-checked{
    background: #E8F4ED;
    border: 1px solid #22944E;
  }
  .is-checked .el-radio__label {
    color: #22944E;
  }
  .el-radio img, .el-checkbox img{
    max-width: 200px;
    max-height: 200px;
    border: #dcdfe6 1px dotted;
  }
  /deep/
  .el-checkbox__inner {
    display: none;
  }
  /deep/
  .el-radio__inner{
    display: none;
  }
  /deep/
  .el-checkbox__label{
    line-height: 30px;
  }
  /deep/
  .el-radio__label {
    line-height: 30px;
    font-size: 16px;
  }
  .datika /deep/ .el-card__body {
    padding: 0
  }
  /deep/ .el-tag {
    width: 40px;
    height: 40px;
    text-align: center;
    line-height: 40px;
    font-size: 18px;
  }
</style>

